<template>
  <div class="coupon-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true" label-width="80px">
        <el-form-item label="优惠券名称">
          <el-input
            v-model="searchForm.title"
            placeholder="请输入优惠券名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型" clearable style="width: 150px">
            <el-option
              v-for="item in couponTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option
              v-for="item in couponStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <el-card class="operation-card">
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增优惠券
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            :disabled="selectedIds.length === 0"
            @click="handleBatchDelete"
          >
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" @click="handleUpdateExpired">
            <el-icon><Refresh /></el-icon>
            更新过期状态
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="couponList"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="优惠券名称" min-width="150" />
        <el-table-column prop="typeName" label="类型" width="120" />
        <el-table-column prop="amount" label="优惠金额" width="100">
          <template #default="{ row }">
            <span v-if="row.type === 1">¥{{ row.amount }}</span>
            <span v-else-if="row.type === 2">{{ row.amount }}%</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="minSpend" label="最低消费" width="100">
          <template #default="{ row }">
            <span v-if="row.minSpend">¥{{ row.minSpend }}</span>
            <span v-else>无限制</span>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="180" />
        <el-table-column prop="endTime" label="结束时间" width="180" />
        <el-table-column prop="statusName" label="状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getStatusTagType(row.status)"
              :effect="row.expiringSoon ? 'dark' : 'light'"
            >
              {{ row.statusName }}
              <span v-if="row.expiringSoon">⚠️</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remainingCount" label="剩余数量" width="100" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button
              v-if="row.status === 0"
              type="success"
              size="small"
              @click="handleActivate(row.id)"
            >
              激活
            </el-button>
            <el-button
              v-if="row.status === 1"
              type="warning"
              size="small"
              @click="handleDeactivate(row.id)"
            >
              停用
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="searchForm.pageNum"
        v-model:page-size="searchForm.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSearch"
        @current-change="handleSearch"
        style="margin-top: 20px; text-align: right"
      />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <CouponDialog
      v-model:visible="dialogVisible"
      :form-data="currentCoupon"
      :is-edit="isEdit"
      @success="handleDialogSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Refresh } from '@element-plus/icons-vue'
import {
  getCouponPage,
  deleteCoupon,
  activateCoupon,
  deactivateCoupon,
  batchDeleteCoupons,
  updateExpiredCoupons,
  couponTypeOptions,
  couponStatusOptions
} from '@/api/coupon'
import CouponDialog from './components/CouponDialog.vue'

// 响应式数据
const loading = ref(false)
const couponList = ref([])
const total = ref(0)
const selectedIds = ref([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentCoupon = ref({})

// 搜索表单
const searchForm = reactive({
  pageNum: 1,
  pageSize: 10,
  title: '',
  type: null,
  status: null
})

// 获取优惠券列表
const getCouponList = async () => {
  loading.value = true
  try {
    const { data } = await getCouponPage(searchForm)
    couponList.value = data.records
    total.value = data.total
  } catch (error) {
    ElMessage.error('获取优惠券列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  searchForm.pageNum = 1
  getCouponList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    pageNum: 1,
    pageSize: 10,
    title: '',
    type: null,
    status: null
  })
  getCouponList()
}

// 新增
const handleAdd = () => {
  currentCoupon.value = {}
  isEdit.value = false
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  currentCoupon.value = { ...row }
  isEdit.value = true
  dialogVisible.value = true
}

// 删除
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个优惠券吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteCoupon(id)
    ElMessage.success('删除成功')
    getCouponList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 激活
const handleActivate = async (id) => {
  try {
    await activateCoupon(id)
    ElMessage.success('激活成功')
    getCouponList()
  } catch (error) {
    ElMessage.error('激活失败')
  }
}

// 停用
const handleDeactivate = async (id) => {
  try {
    await deactivateCoupon(id)
    ElMessage.success('停用成功')
    getCouponList()
  } catch (error) {
    ElMessage.error('停用失败')
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm('确定要删除选中的优惠券吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await batchDeleteCoupons(selectedIds.value)
    ElMessage.success('批量删除成功')
    selectedIds.value = []
    getCouponList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 更新过期状态
const handleUpdateExpired = async () => {
  try {
    await updateExpiredCoupons()
    ElMessage.success('更新过期状态成功')
    getCouponList()
  } catch (error) {
    ElMessage.error('更新过期状态失败')
  }
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 对话框成功回调
const handleDialogSuccess = () => {
  dialogVisible.value = false
  getCouponList()
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    0: 'info',    // 未激活
    1: 'success', // 已激活
    2: 'danger',  // 已过期
    3: 'warning'  // 已用完
  }
  return typeMap[status] || 'info'
}

// 初始化
onMounted(() => {
  getCouponList()
})
</script>

<style scoped>
.coupon-container {
  padding: 20px;
}

.search-card,
.operation-card,
.table-card {
  margin-bottom: 20px;
}

.search-card .el-form {
  margin-bottom: 0;
}
</style>
